from gis.common import track_logging
from gis.common.django_ext.models import paginate
from gis.common.exceptions import BizException
from itpay.core.agency.errors import ERROR_USER_IN_BLACKLIST
from itpay.core.agency.models import UserBlackList

_LOGGER = track_logging.getLogger(__name__)


def add_blacklist_user(agency_id, user_id, mch_id, remark=None):
    assert agency_id
    assert mch_id
    assert user_id

    if check_in_blacklist(agency_id, mch_id, user_id):
        raise BizException(ERROR_USER_IN_BLACKLIST)

    UserBlackList.objects.create(agency_id=agency_id, mch_id=mch_id, user_id=user_id, remark=remark)

    return dict(agency_id=agency_id, mch_id=mch_id, user_id=user_id)


def delete_blacklist_user(blacklist_id):
    assert blacklist_id
    m_black_list_user = _get_blacklist_user(blacklist_id)
    m_black_list_user.delete()


def _get_blacklist_user(blacklist_id):
    m_black_list_user = UserBlackList.objects.filter(pk=blacklist_id).first()
    return m_black_list_user


def list_blacklist(page_no, page_size, agency_id=None, agency_name=None, parent_id=None, parent_name=None, mch_id=None,
                   user_id=None, created_at_begin=None, created_at_end=None):
    query = UserBlackList.objects.all()
    if agency_id:
        query = query.filter(agency_id=agency_id)
    if agency_name:
        query = query.filter(agency__user_name__contains=agency_name)
    if parent_name:
        query = query.filter(agency__parent__user_name__contains=parent_name)
    if parent_id:
        query = query.filter(agency__parent_id=parent_id)
    if mch_id:
        query = query.filter(mch_id=mch_id)
    if user_id:
        query = query.filter(user_id=user_id)
    if created_at_begin:
        query = query.filter(created_at__gte=created_at_begin)
    if created_at_end:
        query = query.filter(created_at__lte=created_at_end)
    return query.count(), [e.to_dict() for e in paginate(query.order_by('-created_at'), page_no, page_size)]


# 检查代理是否拉黑用户
def check_in_blacklist(agency_id, mch_id, user_id):
    return UserBlackList.objects.filter(agency_id=agency_id, mch_id=mch_id, user_id=user_id).exists()


def get_agencies_by_user(mch_id, user_id):
    return list(UserBlackList.objects.filter(mch_id=mch_id, user_id=user_id).values_list("agency_id", flat=True))
